package com.example.attempt.controller;

import com.example.attempt.entity.*;
import com.example.attempt.service.impl.*;
import com.example.attempt.utils.CalculateSimilar;
import okhttp3.*;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
public class SubmitController {

    @Autowired
    private SubmitServiceImpl submitImpl;
    @Autowired
    private StudentServiceImpl studentImpl;
    @Autowired
    private HomeworkServiceImpl homeworkImpl;
    @Autowired
    private GradeServiceImpl gradeImpl;
    @Autowired
    private AssessmentServiceImpl assessmentImpl;

    private final String mypath="D:\\IDEA\\mutual-evaluation\\src\\main\\resources\\submit\\";

    @PostMapping(path = "/queryBySubId")
    public Submit queryBySubId(@RequestParam(value = "submitId") int submitId){
        return submitImpl.queryBySubId(submitId);
    }

    @PostMapping(path = "/getSubIdByHid")
    public List<Integer> getSubIdByHid(@RequestParam(value = "hid") int hid){
        return submitImpl.getSubIdByHid(hid);
    }

    @PostMapping(path = "/getSidBySubId")
    public String getSidBySubId(@RequestParam(value = "submitId") int submitId){
        return submitImpl.queryBySubId(submitId).getSid();
    }

    @PostMapping(path = "/getSubmitNumber")
    public int getSubmitNumber(int hid){
        return submitImpl.getSubmitNumber(hid);
    }
    public boolean isOutOfDdl(SubmitWithFile submitWithFile){
        LocalDateTime ddl=homeworkImpl.queryByHid(submitWithFile.getHid()).getHTime();
        LocalDateTime submitTime=submitWithFile.getSubmit_time();
        return submitTime.isAfter(ddl);
    }
    public boolean isOutOfDdl(Submit submit){
        LocalDateTime ddl=homeworkImpl.queryByHid(submit.getHid()).getHTime();
        LocalDateTime submitTime=submit.getSubmit_time();
        return submitTime.isAfter(ddl);
    }

    @PostMapping(path = "/isSubmitted")
    public int isSubmitted(@RequestParam(value = "sid") String sid,@RequestParam(value = "hid") int hid){
        List<Integer> submits=submitImpl.getSubIdByHid(hid);
        for (Integer m : submits) {
            Submit submit = submitImpl.queryBySubId(m.intValue());
            if (submit.getSid().equals(sid)) {
                return 1;
            }
        }
        return 0;
    }

    @PostMapping("/getSubmitBySidAndHid")
    public Submit getSubmitBySidAndHid(@RequestParam(value = "hid") int hid,@RequestParam(value = "sid")String sid){
        System.out.println("11111111111111111111111");
        Submit submit=submitImpl.queryBySidAndHid(hid,sid);
        System.out.println(submit);
        return submit;
    }

    @PostMapping("/getSubmitBySubid")
    public Submit getSubmitBySubid(@RequestParam(value = "subid") int subid){
        return submitImpl.queryBySubId(subid);
    }

    @PostMapping("/getSubmitsByHid")
    public List<Student> getSubmits(@RequestParam(value = "hid") int hid){
        List<Submit> submits= submitImpl.getByHid(hid);
        List<Student> students=new ArrayList<>();
        for (Submit st : submits) {
            Student s = studentImpl.queryById(st.getSid());
            s.setSpwd("" + hid);
            students.add(s);
        }

        return students;
    }

    @PostMapping("/getHighSubmit")
    public List<Submit> getHighSubmit(@RequestParam(value = "hid") int hid){
        double threshold = homeworkImpl.queryByHid(hid).getThreshold();
        System.out.println(threshold);
        List<Submit> high = submitImpl.getHighSubmit(threshold*100);
        System.out.println(high);
        return high;
    }

    @PostMapping("/cancelCheck")
    public int cancelCheck(@RequestParam(value = "hid") int hid){
        homeworkImpl.updateIsCheck(hid, 0);
        List<Submit> submits = submitImpl.getByHid(hid);
        for(Submit submit : submits){
            submitImpl.updateSimilarity(submit.getSubmitId(), 0);
        }
        return 0;
    }

    @PostMapping("/cancelAllHighGrade")
    public int cancelAllHighGrade(@RequestParam(value = "hid") int hid){
        List<Submit> high = getHighSubmit(hid);
        //更改成绩为0分
        for (Submit submit : high){
            String sid = submit.getSid();
            gradeImpl.updateGrade(hid, sid, 0);
        }
        return 0;
    }

    @PostMapping("/cancelGrade")
    public int cancelGrade(@RequestParam(value = "submitId") int submitId){
        if (submitImpl.queryBySubId(submitId)==null)
            return -1;

        //更改成绩为0分
        gradeImpl.updateGrade(submitImpl.queryBySubId(submitId).getHid(),
                submitImpl.queryBySubId(submitId).getSid(), 0);
        return 0;
    }

    @PostMapping(path = "/deleteSubmit")
    public int deleteSubmit(@RequestParam(value = "submitId") int subid){

        Submit submit=submitImpl.queryBySubId(subid);
        if (submit==null){
            return 0;
        }
        String sPath=mypath+submit.getSubmitId();
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        System.out.println(sPath);
        //如果dir对应的文件不存在，或者不是一个目录，则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return -1;
        }
        //删除文件夹下的所有文件(包括子目录)
        File[] files = dirFile.listFiles();
        for (File file : files) {
            System.out.println(file.getName());
            //删除子文件
            System.out.println(file.delete());
        }
        dirFile.delete();
        submitImpl.deleteSubmit(subid);
        return 1;
    }
    @PostMapping(path = "/addSubmit1")
    public int addSubmit1(@RequestParam(value = "hid") int hid,
                          @RequestParam(value = "sid") String sid,
                          @RequestParam(value = "content") String submit_content
                          ){
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime submit_time = LocalDateTime.now();
        Submit submit=new Submit(0,hid,sid,submit_time,submit_content," ",0);
        String link = "";
        if (homeworkImpl.queryByHid(hid)==null){
            return -2;
        }
        Submit s=submitImpl.queryBySidAndHid(hid,sid);
        System.out.println(s.getSubmitId());
        if(s!=null){
            System.out.println("link"+s.getSubmit_link());
            if(!s.getSubmit_link().equals(" ")){
                String sPath=mypath+s.getSubmitId();
                if (!sPath.endsWith(File.separator)) {
                    sPath = sPath + File.separator;
                }
                File dirFile = new File(sPath);
                System.out.println(sPath);
                //如果dir对应的文件不存在，或者不是一个目录，则退出
                if (!dirFile.exists() || !dirFile.isDirectory()) {
                    return -1;
                }
                boolean flag = true;
                //删除文件夹下的所有文件(包括子目录)
                File[] files = dirFile.listFiles();
                for (int i = 0; i < files.length; i++) {
                    System.out.println(files[i].getName());
                    //删除子文件
                    System.out.println(files[i].delete());
                }
                dirFile.delete();
            }

            System.out.println("subid"+submitImpl.deleteSubmit(s.getSubmitId()));
        }
        if (isOutOfDdl(submit)){
            return -2;
        }
        submitImpl.addSubmit(submit);
        Grade grade = new Grade();
        grade.setSubmitId(submitImpl.queryBySidAndHid(submit.getHid(),submit.getSid()).getSubmitId());
        if(gradeImpl.addGrade(grade)==0)
            return 0;
        Assessment asse = new Assessment();
        asse.setSubmitId(submitImpl.queryBySidAndHid(submit.getHid(),submit.getSid()).getSubmitId());
        asse.setTid(homeworkImpl.queryByHid(submit.getHid()).getTid());
        if(assessmentImpl.addAsse(asse)==0)
            return 0;
        return -1;

    }
    @PostMapping(path = "/addSubmit")
    @ResponseBody
    public int addSubmit(SubmitWithFile submitWithFile){
        Submit submit;
        submitWithFile.getTime();
        System.out.println(submitWithFile);
        String link = "";
        String sid=submitWithFile.getSid();
        int hid=submitWithFile.getHid();
        if (homeworkImpl.queryByHid(submitWithFile.getHid())==null){
            return -2;
        }
        Submit s=submitImpl.queryBySidAndHid(hid,sid);
        if(s!=null){
            if (!s.getSubmit_link().equals(" ")){
                String sPath=mypath+s.getSubmitId();
                if (!sPath.endsWith(File.separator)) {
                    sPath = sPath + File.separator;
                }
                File dirFile = new File(sPath);
                System.out.println(sPath);
                //如果dir对应的文件不存在，或者不是一个目录，则退出
                if (!dirFile.exists() || !dirFile.isDirectory()) {
                    return -1;
                }
                boolean flag = true;
                //删除文件夹下的所有文件(包括子目录)
                File[] files = dirFile.listFiles();
                for (File file : files) {
                    System.out.println(file.getName());
                    //删除子文件
                    System.out.println(file.delete());
                }
                dirFile.delete();
            }
            submitImpl.deleteSubmit(s.getSubmitId());
        }

        MultipartFile multifile = submitWithFile.getSFile();

        if (isOutOfDdl(submitWithFile)){
            return -1;
        }
        s=new Submit(submitWithFile," ",0);
        submitImpl.addSubmit(s);
        if (multifile == null){
            link = "";
        }
        else{
            System.out.println(s);
            s=submitImpl.queryBySidAndHid(hid,sid);
            try {
                String filePath1 = mypath+s.getSubmitId();
                //生成文件夹
                File file1 = new File(filePath1);
                if(!file1.exists()){	//如果_test2文件夹不存在
                    file1.mkdir();		//创建文件夹
                }
                InputStream inputStream = multifile.getInputStream();
                String filePath = filePath1 +"\\"+ multifile.getOriginalFilename();
                OutputStream outputStream = new FileOutputStream(filePath);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer,0,len);
                }
                InetAddress localHost = InetAddress.getLocalHost();
                link = localHost.getHostAddress();
                link = "http://lyycf.natapp1.cc/submit/"+s.getSubmitId()+"/"+multifile.getOriginalFilename();
                inputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        submitImpl.updateLink(s.getSubmitId(),link);

            Grade grade = new Grade();
            grade.setSubmitId(submitImpl.queryBySidAndHid(s.getHid(),s.getSid()).getSubmitId());
            if(gradeImpl.addGrade(grade)==0)
                return 0;
            Assessment asse = new Assessment();
            asse.setSubmitId(submitImpl.queryBySidAndHid(s.getHid(),s.getSid()).getSubmitId());
            asse.setTid(homeworkImpl.queryByHid(s.getHid()).getTid());
            if(assessmentImpl.addAsse(asse)==0)
                return 0;

        return -1;

    }
    @PostMapping(path = "/checkDuplicates1")
    public int checkDuplicates1(@RequestParam(value = "hid") int hid) throws IOException {
        List<Integer> subIds = submitImpl.getSubIdByHid(hid);
        //获取文件夹路径
        List<String> folderPaths = new ArrayList<>();
        for(int id : subIds){
//            String sid = submitImpl.queryBySubId(id).getSid();
//            folderPaths.add(mypath+sid+"to"+hid); //文件路径
            folderPaths.add(mypath+id);
        }

        //获取所有文件路径
        List<String> allFilePaths = new ArrayList<>();
        for (String folderPath : folderPaths) {
            List<String> filePathsInFolder = listFiles(folderPath);
            allFilePaths.addAll(filePathsInFolder);
        }

        // 打印所有文件路径
        for (String filePath : allFilePaths) {
            System.out.println(filePath);
        }

        //相似度比较
        double [][] similarities = new double[subIds.size()][subIds.size()];
        for(int i = 0; i < subIds.size(); i++){
            similarities[i][i] = 0;
            for(int j = i + 1; j < subIds.size(); j++){
                String path = allFilePaths.get(i);
                String path1 = allFilePaths.get(j);
                System.out.println(path+"  "+path1+"   ");
                double similarity = CalculateSimilar.getSimilarResult1(path,path1);
                System.out.println(path+"  "+path1+"   "+similarity);
                BigDecimal two = new BigDecimal(similarity);
                similarity = two.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue(); //保留1位小数
                similarities[i][j] = similarity;
                similarities[j][i] = similarity;
            }
        }
        System.out.println(subIds);
        //打印
        for(int i = 0; i < subIds.size(); i++){
            for(int j = 0; j < subIds.size(); j++){
                System.out.print(i+" "+j+similarities[i][j] + " ,");
            }
            Arrays.sort(similarities[i]);
            double result = similarities[i][similarities[i].length-1];
            //更新数据库
            submitImpl.updateSimilarity(subIds.get(i), result);
            System.out.println("result: " + result);
            homeworkImpl.updateIsCheck(hid, 1);
        }
        return 0;
    }
    @PostMapping(path = "/checkDuplicates")
    public int checkDuplicates(@RequestParam(value = "hid") int hid) throws IOException {
        List<Integer> subIds = submitImpl.getSubIdByHid(hid);
        //获取文件夹路径
        List<String> folderPaths = new ArrayList<>();
        for(int id : subIds){
//            String sid = submitImpl.queryBySubId(id).getSid();
//            folderPaths.add(mypath+sid+"to"+hid); //文件路径
            folderPaths.add(mypath+id);
        }

        //获取所有文件路径
        List<String> allFilePaths = new ArrayList<>();
        for (String folderPath : folderPaths) {
            List<String> filePathsInFolder = listFiles(folderPath);
            allFilePaths.addAll(filePathsInFolder);
        }

        // 打印所有文件路径
        for (String filePath : allFilePaths) {
            System.out.println(filePath);
        }

        //相似度比较
        double [][] similarities = new double[subIds.size()][subIds.size()];
        for(int i = 0; i < subIds.size(); i++){
            similarities[i][i] = 0;
            for(int j = i + 1; j < subIds.size(); j++){
                String path = allFilePaths.get(i);
                String path1 = allFilePaths.get(j);
                double similarity = CalculateSimilar.getSimilarResult(path,path1);
                BigDecimal two = new BigDecimal(similarity);
                similarity = two.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue(); //保留1位小数
                similarities[i][j] = similarity;
                similarities[j][i] = similarity;
            }
        }
        //打印
        System.out.println("打印相似度矩阵");
        for(int i = 0; i < subIds.size(); i++){
            for(int j = 0; j < subIds.size(); j++){
                System.out.println(i+" "+j+" "+similarities[i][j] + " ,");
            }
            Arrays.sort(similarities[i]);
            double result = similarities[i][similarities[i].length-1];
            //更新数据库
            submitImpl.updateSimilarity(subIds.get(i), result);
            System.out.println("result: " + result);
            homeworkImpl.updateIsCheck(hid, 1);
        }
        return 0;
    }

    private static List<String> listFiles(String folderPath) {
        List<String> filePaths = new ArrayList<>();
        File folder = new File(folderPath);

        File[] files = folder.listFiles();

        if (files != null) {
            for (File file : files) {
                if (file.isFile())
                    filePaths.add(file.getAbsolutePath());
            }
        }
        return filePaths;
    }
    @PostMapping(path = "/testflask")
    public String test() {
        String responseBody="";
        // 创建URL对象
        String sentence1 = "阿宁可爱捏";
        String sentence2 = "山外青山楼外楼";

        // 创建OkHttpClient实例
        OkHttpClient client = new OkHttpClient();

        // 构建请求体
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("sentence1", sentence1);
        jsonBody.put("sentence2", sentence2);

        RequestBody requestBody = RequestBody.create(
                MediaType.parse("application/json"),
                jsonBody.toString()
        );
        // 创建POST请求
        Request request = new Request.Builder()
                .url("http://172.30.76.122:5000/predict")
                .post(requestBody)
                .build();

        try {
            // 发送请求并获取响应
            Response response = client.newCall(request).execute();

            // 解析响应体
            if (response.isSuccessful()) {
                responseBody = response.body().string();
                // 解析返回的similarity值

            } else {
                System.out.println("Request failed with code: " + response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseBody;
    }
}
